package com.google.code.sip.ucenter.ws.resources;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.code.sip.ucenter.model.Credit;
import com.google.code.sip.ucenter.model.CreditLog;
import com.google.code.sip.ucenter.model.CreditOperation;
import com.google.code.sip.ucenter.model.CreditRule;
import com.google.code.sip.ucenter.model.CreditRuleAmount;
import com.google.code.sip.ucenter.model.CreditRuleLog;
import com.google.code.sip.ucenter.model.CreditType;
import com.google.code.sip.ucenter.model.Setting;
import com.google.code.sip.ucenter.model.User;
import com.google.code.sip.ucenter.service.CreditLogManager;
import com.google.code.sip.ucenter.service.CreditManager;
import com.google.code.sip.ucenter.service.CreditRuleManager;
import com.google.code.sip.ucenter.service.CreditTypeManager;
import com.google.code.sip.ucenter.service.SettingManager;
import com.google.code.sip.ucenter.service.UserManager;
import com.google.code.sip.ucenter.ws.WSResponse;
import com.google.code.sip.ucenter.ws.WSResponseStatus;
import com.google.code.sip.ucenter.ws.dto.CreditDto;
import com.google.code.sip.ucenter.ws.dto.CreditLogDto;
import com.google.code.sip.ucenter.ws.dto.CreditRuleDto;
import com.google.code.sip.ucenter.ws.dto.CreditRuleLogDto;
import com.google.code.sip.ucenter.ws.dto.CreditTypeDto;
import com.google.code.sip.ucenter.ws.dto.SettingDto;
import com.sun.jersey.spi.resource.Singleton;

@Component
@Path("/credit")
@Singleton
@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public class CreditResource extends AbstractResource {

	@Autowired
	private UserManager userManager;
	@Autowired
	private SettingManager settingManager;
	@Autowired
	private CreditRuleManager creditRuleManager;
	@Autowired
	private CreditManager creditManager;
	@Autowired
	private CreditTypeManager creditTypeManager;
	@Autowired
	private CreditLogManager creditLogManager;

	private final Log logger = LogFactory.getLog(getClass());

	@POST
	@Path("/count")
	public WSResponse<String> getCreditCount(@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		User user = null;
		try {
			user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			int creditCount = userManager.getCreditCount(user);
			return new WSResponse<String>(String.valueOf(creditCount));
		} catch (RuntimeException e) {
			logger.error(e.getMessage() + user, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}
	}

	@POST
	@Path("/list")
	public WSResponse<CreditDto> getCredits(@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<CreditDto>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			List<Credit> creditsList = creditManager.getCreditesByUser(user);
			if (creditsList == null || creditsList.isEmpty()) {
				return new WSResponse<CreditDto>();
			}
			List<CreditDto> dtos = new ArrayList<CreditDto>(creditsList.size());
			for (Credit credit : creditsList) {
				CreditDto creditDto = new CreditDto();
				BeanUtils.copyProperties(credit, creditDto);
				creditDto.setUserId(credit.getUser().getId());
				creditDto.setCreditTypeId(credit.getCreditType().getId());
				dtos.add(creditDto);
			}
			return new WSResponse<CreditDto>(dtos);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<CreditDto>(WSResponseStatus.SERVER_ERROR);
		}
	}

	@POST
	@Path("/history")
	public WSResponse<CreditLogDto> getCreditLogs(
			@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<CreditLogDto>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			List<CreditLog> creditLogsList = creditManager.getCreditLogs(user);
			if (creditLogsList == null || creditLogsList.isEmpty()) {
				return new WSResponse<CreditLogDto>();
			}
			List<CreditLogDto> dtos = new ArrayList<CreditLogDto>(
					creditLogsList.size());
			for (CreditLog creditLog : creditLogsList) {
				CreditLogDto creditLogDto = new CreditLogDto();
				BeanUtils.copyProperties(creditLog, creditLogDto);
				dtos.add(creditLogDto);
			}
			return new WSResponse<CreditLogDto>(dtos);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<CreditLogDto>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("/grant")
	public WSResponse<String> grantCredit(@FormParam("userId") String userId,
			@FormParam("action") String action,
			@DefaultValue("") @FormParam("remark") String remark) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != action) : "action cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			CreditRule creditRule = creditRuleManager
					.getCreditRuleByAction(action);
			if (creditRule == null) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"该动作对应的积分规则不存在。"));
			}
			CreditRuleLog creditRuleLog = creditManager.getCreditRuleLog(user,
					creditRule);
			if (creditRuleLog != null
					&& !creditManager.canGrantCredit(creditRule, creditRuleLog)) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"该动作的对应的积分计算次数已超出限制。"));
			}
			creditManager.grantCredit(user, action, remark);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("/buy")
	public WSResponse<String> consumeCredit(@FormParam("userId") String userId,
			@FormParam("creditOperation") CreditOperation creditOperation,
			@FormParam("amount") int amount,
			@DefaultValue("") @FormParam("remark") String remark) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != creditOperation) : "creditOperation cann't be null.";
		assert (amount >= 0) : "amount must than 0.";
		try {

			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			CreditType creditType = getTransCreditType();
			if (creditType == null) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"没有设置交易积分类型。"));
			}
			if (!creditType.isAvailable()) {
				return new WSResponse<String>(new WSResponseStatus(-5,
						"交易积分类型是无效状态，不可使用。"));
			}
			if (amount <= 0) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"消费积分必须大于0。"));
			}
			// 判断用户金金钱积分是否够用
			Credit credit = creditManager.getOrCreateCredit(user, creditType);
			if (credit.getAmount() < amount) {
				return new WSResponse<String>(new WSResponseStatus(-4,
						"用户无足够积分进行消费。"));
			}

			// 修改用户积分 返回积分日志ID
			String transactionId = creditManager.buy(credit, creditOperation,
					amount, remark);
			return new WSResponse<String>(transactionId);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("cancelBuy")
	// @Path("/cancelConsume")
	public WSResponse<String> cancelConsumeCredit(
			@FormParam("userId") String userId,
			@FormParam("transactionId") String transactionId,
			@FormParam("creditOperation") CreditOperation creditOperation,
			@DefaultValue("false") @FormParam("deductedTax") boolean deductedTax) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != transactionId) : "transactionId cann't be null.";
		try {

			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			CreditType creditType = getTransCreditType();
			if (creditType == null) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"没有设置交易积分。"));
			}
			if (!creditType.isAvailable()) {
				return new WSResponse<String>(new WSResponseStatus(-5,
						"交易积分类型是无效状态，不可使用。"));
			}
			CreditLog creditLog = creditLogManager.getCreditLog(transactionId);
			if (creditLog != null) {
				// 判断是否已经进行过取消操作
				if (creditLog.getCanceled() != null && creditLog.getCanceled()) {
					return new WSResponse<String>(new WSResponseStatus(-3,
							"已经进行过取消操作，不能重复操作。"));
				}
				// 判断操作用户是不是本人
				if (!creditLog.getUsername().equals(user.getUsername())) {
					return new WSResponse<String>(new WSResponseStatus(-4,
							"不是消费者本人。"));
				}
				creditManager.cancelBuy(user, creditType, transactionId,
						deductedTax, creditOperation);
			}
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("/gain")
	public WSResponse<String> gainCredit(
			@FormParam("userId") String userId,
			@FormParam("creditOperation") CreditOperation creditOperation,
			@FormParam("amount") int amount,
			@DefaultValue("false") @FormParam("deductedTax") boolean deductedTax,
			@DefaultValue("") @FormParam("remark") String remark) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != creditOperation) : "creditOperation cann't be null.";
		assert (amount >= 0) : "amount must than 0.";
		try {

			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			CreditType creditType = getTransCreditType();
			if (creditType == null) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"没有设置交易积分。"));
			}
			if (!creditType.isAvailable()) {
				return new WSResponse<String>(new WSResponseStatus(-4,
						"交易积分类型是无效状态，不可使用。"));
			}
			if (amount <= 0) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"消费积分必须大于0。"));
			}
			creditManager.gainCredit(user, creditType, creditOperation,
					deductedTax, amount, remark);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}
	}

	@POST
	@Path("/trans")
	public WSResponse<String> transCredit(
			@FormParam("outUserId") String outUserId,
			@FormParam("inUserId") String inUserId,
			@FormParam("amount") int amount,
			@DefaultValue("") @FormParam("remark") String remark) {
		assert (null != outUserId) : "outUserId cann't be null.";
		assert (null != inUserId) : "inUserId cann't be null.";
		assert (0 != amount) : "amount cann't be zero.";
		try {

			User outUser = userManager.getUser(outUserId);
			if (outUser == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"积分转出用户不存在。"));
			}

			User inUser = userManager.getUser(inUserId);
			if (inUser == null) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"积分转入用户不存在。"));
			}

			CreditType creditType = getTransCreditType();
			if (creditType == null) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"没有设置交易积分。"));
			}

			if (!creditType.isAvailable()) {
				return new WSResponse<String>(new WSResponseStatus(-7,
						"交易积分类型是无效状态，不可使用。"));
			}

			// 转出的积分
			Credit outCredit = creditManager.getCredit(outUser, creditType);
			if (outCredit == null) {
				return new WSResponse<String>(new WSResponseStatus(-4,
						"积分转出用户无转让积分。"));
			}
			Setting creditTransferMinSetting = settingManager
					.getSettingByName(Setting.CREDIT_TRANSFER_MIN_AMOUNT);
			// 最小转让金额
			int creditTransferMin = creditTransferMinSetting != null ? Integer
					.parseInt(creditTransferMinSetting.getValue()) : 0;
			if (outCredit.getAmount() < creditTransferMin) {
				return new WSResponse<String>(new WSResponseStatus(-5,
						"积分转出用户无足够积分进行转让。"));
			}
			Setting creditTransferMinBalanceSetting = settingManager
					.getSettingByName(Setting.CREDIT_TRANSFER_MIN_AMOUNT);
			// 转让后的最小余额
			int creditTransferMinBalance = creditTransferMinBalanceSetting != null ? Integer
					.parseInt(creditTransferMinBalanceSetting.getValue())
					: 0;
			if (outCredit.getAmount() - amount <= creditTransferMinBalance) {
				return new WSResponse<String>(new WSResponseStatus(-6,
						"积分转出用户转帐后的余额不足。"));
			}
			// 转入的积分
			Credit intCredit = creditManager.getOrCreateCredit(inUser,
					creditType);
			creditManager.transferCredit(outCredit, intCredit, amount, remark);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}
	}

	@POST
	@Path("/charge")
	public WSResponse<String> chargeCredit(@FormParam("userId") String userId,
			@FormParam("money") double money,
			@DefaultValue("") @FormParam("remark") String remark) {
		assert (null != userId) : "userId cann't be null.";
		assert (money > 0) : "money cann't lessthan 0.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			// 查找交易积分类型
			Setting creditTransferSetting = settingManager
					.getSettingByName(Setting.CREDIT_TRANSFER);

			if (StringUtils.isBlank(creditTransferSetting.getValue())) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"没有设置交易积分。"));
			}

			// 查找现金/积分兑换比率
			Setting creditChargeRatio = settingManager
					.getSettingByName(Setting.CREDIT_CHARGE_RATIO);
			if (StringUtils.isBlank(creditChargeRatio.getValue())) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"没有设置现金/积分兑换比率。"));
			}

			String creditTypeName = creditTransferSetting.getValue();
			CreditType creditType = creditTypeManager
					.getCreditTypeByName(creditTypeName);
			if (creditType == null) {
				return new WSResponse<String>(new WSResponseStatus(-4,
						"设置好的交易积分不存在。"));
			}

			if (!creditType.isAvailable()) {
				return new WSResponse<String>(new WSResponseStatus(-9,
						"交易积分类型是无效状态，不可使用。"));
			}

			// 获取本地充值的积分数
			int inAmount = (int) (money * (Integer.valueOf(creditChargeRatio
					.getValue())));

			// 单次购买最小积分数额：
			Setting creditChargeMinSetting = settingManager
					.getSettingByName(Setting.CREDIT_CHARGE_RATIO);
			String creditChargeMin = creditChargeMinSetting.getValue();
			if (StringUtils.isBlank(creditChargeMin)) {
				return new WSResponse<String>(new WSResponseStatus(-5,
						"没有设置单次购买最小积分数额。"));
			}
			if (!creditChargeMin.equals("0")) {
				if (inAmount < Integer.valueOf(creditChargeMin)) {
					return new WSResponse<String>(new WSResponseStatus(-6,
							"购买积分小于最小单次购买积分。"));
				}
			}

			// 单次购买最大积分数额：
			Setting creditChargeMaxSetting = settingManager
					.getSettingByName(Setting.CREDIT_CHARGE_MAX);
			String creditChargeMax = creditChargeMaxSetting.getValue();
			if (StringUtils.isBlank(creditChargeMax)) {
				return new WSResponse<String>(new WSResponseStatus(-7,
						"没有设置单次购买最大积分数额。"));
			}
			if (!creditChargeMax.equals("0")) {
				if (inAmount > Integer.valueOf(creditChargeMax)) {
					return new WSResponse<String>(new WSResponseStatus(-8,
							"购买积分大于于最小单次购买积分。"));
				}
			}

			// 每月购买最大积分数额：
			// Setting creditChargeMaxPermonthSetting =
			// settingManager.getSettingByName(Setting.CREDIT_CHARGE_MAX_PERMONTH);

			creditManager.chargeCredit(user, money, creditType, Integer
					.valueOf(creditChargeRatio.getValue()), remark);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("sell")
	// @Path("/exchange")
	public WSResponse<String> sell(
			@FormParam("userId")// exchangeCredit(@FormParam("userId")
			String userId, @FormParam("amount") int amount,
			@DefaultValue("") @FormParam("remark") String remark) {
		assert (null != userId) : "userId cann't be null.";
		assert (amount > 0) : "amount cann't lessthan 0.";
		try {

			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			// 查找交易积分类型
			Setting creditTransferSetting = settingManager
					.getSettingByName(Setting.CREDIT_TRANSFER);

			if (StringUtils.isBlank(creditTransferSetting.getValue())) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"没有设置交易积分。"));
			}
			String creditTypeName = creditTransferSetting.getValue();
			CreditType creditType = creditTypeManager
					.getCreditTypeByName(creditTypeName);
			if (creditType == null) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"设置好的交易积分不存在。"));
			}
			if (!creditType.isAvailable()) {
				return new WSResponse<String>(new WSResponseStatus(-4,
						"交易积分类型是无效状态，不可使用。"));
			}
			// 判断用户兑换后的积分余额是否小于系统设置的 积分兑换最低余额
			// Setting creditExchangeMinBalanceSetting =
			// settingManager.getSettingByName(Setting.CREDIT_EXCHANGE_MIN_BALANCE);
			// if
			// (StringUtils.isBlank(creditExchangeMinBalanceSetting.getValue()))
			// {
			// return new WSResponse<String>(new WSResponseStatus(-4,
			// "没有设置积分兑换最低余额。"));
			// }
			//		
			// Setting creditTansferTaxSetting =
			// settingManager.getSettingByName(Setting.CREDIT_TAX);
			// double creditTansferTax = creditTansferTaxSetting != null ?
			// Double.parseDouble(creditTansferTaxSetting.getValue()) : 0d;
			// if (creditTansferTax != 0) {
			// amount = (int) (amount * (1 - creditTansferTax));
			// }
			//		
			// Credit credit = creditManager.getCredit(user, creditType);
			// if((credit.getAmount()-amount)<Integer.valueOf(creditExchangeMinBalanceSetting.getValue())){
			// return new WSResponse<String>(new WSResponseStatus(-5,
			// "兑换后的积分小于系统设置的积分兑换后最低余额。"));
			// }
			creditManager.sell(user, creditType, amount, remark);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}
	}

	// ------------------------add following
	@POST
	@Path("/exchange")
	public WSResponse<String> exchangeCredit(
			@FormParam("userId") String userId,
			@FormParam("creditTypeNameFrom") String creditTypeNameFrom,
			@FormParam("amount") int amount,
			@FormParam("creditTypeNameTo") String creditTypeNameTo,
			@DefaultValue("") @FormParam("remark") String remark) {
		assert (null != userId) : "userId cann't be null.";
		assert (amount > 0) : "amount cann't lessthan 0.";
		try {

			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}

			// 查找兑出交易积分类型
			CreditType creditTypeFrom = creditTypeManager
					.getCreditTypeByName(creditTypeNameFrom);
			if (creditTypeFrom == null) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"兑出积分类型不存在。"));
			}

			if (!creditTypeFrom.isAvailable()) {
				return new WSResponse<String>(new WSResponseStatus(-6,
						"兑出积分类型是无效状态，不可使用。"));
			}

			if (!creditTypeFrom.isAllowExchangeOut()
					|| creditTypeFrom.getRatio() == 0) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"兑出积分类型不允许兑出操作。"));
			}

			// 查询兑入交易积分类型
			CreditType creditTypeTo = creditTypeManager
					.getCreditTypeByName(creditTypeNameTo);
			if (creditTypeTo == null) {
				return new WSResponse<String>(new WSResponseStatus(-4,
						"兑入积分类型不存在。"));
			}
			if (!creditTypeTo.isAvailable()) {
				return new WSResponse<String>(new WSResponseStatus(-7,
						"兑入积分类型是无效状态，不可使用。"));
			}

			if (!creditTypeTo.isAllowExchangeIn()
					|| creditTypeTo.getRatio() == 0) {
				return new WSResponse<String>(new WSResponseStatus(-5,
						"兑入积分类型不允许兑入操作。"));
			}

			creditManager.exchange(user, creditTypeFrom, creditTypeTo, amount,
					remark);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}
	}

	// -------------------------------

	@POST
	@Path("/getRuleLog")
	public WSResponse<CreditRuleLogDto> getCreditRuleLog(
			@FormParam("userId") String userId,
			@FormParam("action") String action) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != action) : "action cann't be null.";
		try {

			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<CreditRuleLogDto>(new WSResponseStatus(
						-1, "该用户不存在。"));
			}
			CreditRule creditRule = creditManager.getCreditRuleByAction(action);
			if (creditRule == null) {
				return new WSResponse<CreditRuleLogDto>(new WSResponseStatus(
						-2, "动作对应的积分规则不存在。"));
			}
			CreditRuleLog creditRuleLog = creditManager.getCreditRuleLog(user,
					creditRule);
			if (creditRuleLog == null) {
				return new WSResponse<CreditRuleLogDto>(new WSResponseStatus(
						-3, "对应的积分规则日志不存在。"));
			}
			CreditRuleLogDto dto = new CreditRuleLogDto();
			BeanUtils.copyProperties(creditRuleLog, dto);
			dto.setCreditRuleId(creditRuleLog.getCreditRule().getId());
			dto.setCreditRuleName(creditRuleLog.getCreditRule().getName());
			dto.setCreditRuleAction(creditRuleLog.getCreditRule().getAction());
			return new WSResponse<CreditRuleLogDto>(dto);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<CreditRuleLogDto>(
					WSResponseStatus.SERVER_ERROR);
		}
	}

	@POST
	@Path("/ruleLogs")
	public WSResponse<CreditRuleLogDto> getCreditRuleLogs(
			@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		try {

			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<CreditRuleLogDto>(new WSResponseStatus(
						-1, "该用户不存在。"));
			}
			List<CreditRuleLog> creditRuleLogs = creditManager
					.getAllCreditRuleLog(user);
			if (creditRuleLogs == null || creditRuleLogs.isEmpty()) {
				return new WSResponse<CreditRuleLogDto>();
			}
			List<CreditRuleLogDto> dtos = new ArrayList<CreditRuleLogDto>(
					creditRuleLogs.size());
			for (CreditRuleLog creditRuleLog : creditRuleLogs) {
				CreditRuleLogDto dto = new CreditRuleLogDto();
				BeanUtils.copyProperties(creditRuleLog, dto);
				dto.setCreditRuleId(creditRuleLog.getCreditRule().getId());
				dto.setCreditRuleName(creditRuleLog.getCreditRule().getName());
				dto.setCreditRuleAction(creditRuleLog.getCreditRule()
						.getAction());
				dtos.add(dto);
			}
			return new WSResponse<CreditRuleLogDto>(dtos);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<CreditRuleLogDto>(
					WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("/getType")
	public WSResponse<CreditTypeDto> getCreditType(
			@FormParam("name") String name) {
		assert (null != name) : "name cann't be null.";
		try {
			CreditType type = creditManager.getCreditTypeByName(name);
			if (type == null) {
				return new WSResponse<CreditTypeDto>(new WSResponseStatus(-1,
						"此名称对应的积分类型不存在。"));
			}
			CreditTypeDto dto = new CreditTypeDto();
			BeanUtils.copyProperties(type, dto);
			return new WSResponse<CreditTypeDto>(dto);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<CreditTypeDto>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("/types")
	public WSResponse<CreditTypeDto> getAllCreditTypes() {
		try {
			List<CreditType> types = creditManager.getAllCreditTypes();
			if (types == null || types.isEmpty()) {
				return new WSResponse<CreditTypeDto>(new WSResponseStatus(-1,
						"无积分类型。"));
			}
			List<CreditTypeDto> typeDtos = new ArrayList<CreditTypeDto>(types
					.size());
			for (CreditType type : types) {
				CreditTypeDto dto = new CreditTypeDto();
				BeanUtils.copyProperties(type, dto);
				typeDtos.add(dto);
			}
			return new WSResponse<CreditTypeDto>(typeDtos);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<CreditTypeDto>(WSResponseStatus.SERVER_ERROR);

		}
	}

	@POST
	@Path("/getRule")
	public WSResponse<CreditRuleDto> getCreditRule(
			@FormParam("action") String action) {
		assert (null != action) : "action cann't be null.";
		try {
			CreditRule rule = creditManager.getCreditRuleByAction(action);
			if (rule == null) {
				return new WSResponse<CreditRuleDto>(new WSResponseStatus(-1,
						"此动作对应的积分规则不存在。"));
			}
			CreditRuleDto dto = new CreditRuleDto();
			BeanUtils.copyProperties(rule, dto);
			Set<CreditRuleAmount> creditRuleAmounts = rule
					.getCreditRuleAmounts();
			if (creditRuleAmounts != null && !creditRuleAmounts.isEmpty()) {
				for (CreditRuleAmount creditRuleAmount : creditRuleAmounts) {
					dto.getAmounts().put(
							creditRuleAmount.getCreditType().getTitle(),
							creditRuleAmount.getAmout());
				}
			}
			return new WSResponse<CreditRuleDto>(dto);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<CreditRuleDto>(WSResponseStatus.SERVER_ERROR);

		}

	}

	@POST
	@Path("/rules")
	public WSResponse<CreditRuleDto> getAllCreditRules() {
		try {
			List<CreditRule> rules = creditManager.getAllCreditRules();
			if (rules == null || rules.isEmpty()) {
				return new WSResponse<CreditRuleDto>(new WSResponseStatus(-1,
						"无积分规则。"));
			}
			List<CreditRuleDto> ruleDtos = new ArrayList<CreditRuleDto>(rules
					.size());
			for (CreditRule rule : rules) {
				CreditRuleDto dto = new CreditRuleDto();
				BeanUtils.copyProperties(rule, dto);
				// 复制积分规则值
				// Set<CreditRuleAmount> creditRuleAmounts =
				// rule.getCreditRuleAmounts(); //修改前实现

				// add by fengcai start 2010/6/28
				Set<CreditRuleAmount> creditRuleAmounts = rule
						.getCreditRuleAmounts();
				if (creditRuleAmounts != null && !creditRuleAmounts.isEmpty()) {
					for (CreditRuleAmount creditRuleAmount : creditRuleAmounts) {
						dto.getAmounts().put(
								creditRuleAmount.getCreditType().getTitle(),
								creditRuleAmount.getAmout());
					}
				}
				ruleDtos.add(dto);
			}
			return new WSResponse<CreditRuleDto>(ruleDtos);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<CreditRuleDto>(WSResponseStatus.SERVER_ERROR);
		}
	}

	@POST
	@Path("/settings")
	public WSResponse<SettingDto> getAllCreditSettings() {
		try {
			List<Setting> settings = settingManager
					.getAllSettings(Setting.GROUP_CREDIT);
			if (settings == null || settings.isEmpty()) {
				return new WSResponse<SettingDto>(new WSResponseStatus(-1,
						"无积分系统参数。"));
			}
			List<SettingDto> dtos = new ArrayList<SettingDto>(settings.size());
			for (Setting setting : settings) {
				SettingDto dto = new SettingDto();
				BeanUtils.copyProperties(setting, dto);
				dtos.add(dto);
			}
			return new WSResponse<SettingDto>(dtos);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return new WSResponse<SettingDto>(WSResponseStatus.SERVER_ERROR);
		}
	}

	private CreditType getTransCreditType() {
		try {
			Setting creditTransferSetting = settingManager
					.getSettingByName(Setting.CREDIT_TRANSFER);
			if (creditTransferSetting == null
					|| StringUtils.isBlank(creditTransferSetting.getValue())) {
				return null;
			}

			String creditTypeName = creditTransferSetting.getValue();
			return creditTypeManager.getCreditTypeByName(creditTypeName);
		} catch (RuntimeException e) {
			logger.error(e.getMessage(), e);
			return null;
		}
	}
}
